import {Router, Request, Response} from "express";
import {GamesModel} from "../models/gamesModel";
import {getJson} from "../utils";

require('express-async-errors');

export const game_router: Router = Router();

game_router.get('/names', async (req: Request, res: Response) => {
    // const names = await GamesModel.find({}, {name: 1, _id: 0}).limit(5);
    const is_me = req.query.is_me as string;
    const match: any = {};
    const excludeAppids = await getJson();
    if (is_me === '1') {
        match.appid = {$in: excludeAppids};
    } else {
        match.appid = {$nin: excludeAppids};
    }
    const result = await GamesModel.find(match, {name: 1, _id: 0, appid: 1});
    res.json(result);
});
game_router.get('/all', async (req: Request, res: Response) => {
    const appid = req.query.appid as string;
    const is_me = req.query.is_me as string;
    const select_games = req.query.select_games as string[];
    const match: any = {};
    const excludeAppids = await getJson();
    if (is_me === '1') {
        match.appid = {$in: excludeAppids};
    } else {
        match.appid = {$nin: excludeAppids};
    }
    if (appid && appid !== '') {
        match.appid = appid;
    }
    if (select_games && select_games.length > 0) {
        match.name = {$in: select_games};
    }
    // const pipeline = {match}
    res.json({data: await GamesModel.find(match, {name: 1, appid: 1, config: 1, secret: 1, _id: 0})});
});

game_router.post('/update_video_count', async (req: Request, res: Response) => {
    res.json(await game_update_video_count(req.body.appid, req.body.video));
})

async function game_update_video_count(appid: string, video_count: string) {
    const db_result: any = await GamesModel.findOne({appid: appid});
    let config = db_result.config;
    config.video = video_count;
    return GamesModel.updateOne({appid: appid}, {$set: {config: config}});
}
